package cn.wizzer.framework.base;

import cn.wizzer.framework.base.exceptions.BizException;
import cn.wizzer.framework.util.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Mirror;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by wizzer on 2016/12/21.
 */
public class Result implements Serializable {

    private static final Log log = Logs.get();

    private static final long serialVersionUID = 1L;

    private int code;
    private String msg;
    private Object data;
    private String detail;
    private String key;


    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public Result() {

    }

    public Result(Enum src) {
        Mirror<?> mi = Mirror.me(src);
        try {
            this.code = (int) mi.invoke(src, "value");
        } catch (Exception e1) {
            try {
                this.code = (int) mi.invoke(src, "getValue");
            } catch (Exception e2) {
                this.code = src.ordinal();
            }
        }
        try {
            this.msg = Strings.sNull(mi.invoke(src, "text"));
        } catch (Exception e1) {
            try {
                this.msg = Strings.sNull(mi.invoke(src, "getText"));
            } catch (Exception e2) {
                this.msg = src.name();
            }
        }
    }

    public static Result NEW() {
        return new Result();
    }

    public static void response(HttpServletResponse response, HTTP_STATUS code, Map<String, String> header, byte[] body) {
        response(response,code,header,new String(body));
    }
    public static void response(HttpServletResponse response, HTTP_STATUS code, Map<String, String> header, Object body) {
        response.setStatus(code.CODE);
        if(null != header && header.keySet().size()>0){
            header.forEach(response::setHeader);
        }
        ServletOutputStream outputStream = null;
        try{
            outputStream = response.getOutputStream();
            outputStream.print(body.getClass().equals(String.class)?(String)body:JSONObject.toJSONString(body));
        } catch (IOException e) {
            log.error(e.getMessage());
        }finally {
            if (null != outputStream){
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }


    }

    public static void error(HttpServletResponse response, String content) {
        ServletOutputStream print = null;
        try {
            response.setContentType("text/html; charset=utf-8");
            response.setCharacterEncoding(Charsets.UTF_8.name());
            print = response.getOutputStream();
            print.print(JSONUtil.toJSONString(error(content)));
        } catch (IOException ignore) {
        } finally {
            if (print != null) {
                try {
                    print.flush();
                    print.close();
                } catch (IOException ignore) {
                }
            }
        }
    }


    public static void error(HttpServletResponse response, String content,String detail) {
        if (!(response.getStatus() == 500)){
            ServletOutputStream print = null;
            try {
                response.setContentType("text/html; charset=utf-8");
                response.setCharacterEncoding(Charsets.UTF_8.name());
                print = response.getOutputStream();
                Result error = error(content);
                error.setDetail(detail);
                print.print(JSONUtil.toJSONString(error));
            } catch (IOException ignore) {
            } finally {
                if (print != null) {
                    try {
                        print.flush();
                        print.close();
                    } catch (IOException ignore) {
                    }
                }
            }
        }
    }

    public static void error(HttpServletResponse response) {
        try {
            ServletOutputStream print = response.getOutputStream();
            print.print(JSONUtil.toJSONString(error()));
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    public static void breakWith(String cause) {
        throw BizException.NEW(cause);
    }

    public static <T >ArrayList<T> createList(T... args) {
        ArrayList<T> arrayList = new ArrayList<>();
        arrayList.addAll(Arrays.stream(args).collect(Collectors.toList()));
        return arrayList;
    }


    public Result addCode(int code) {
        this.code = code;
        return this;
    }

    public Result addMsg(String msg) {
        if (Strings.isBlank(msg) || Mvcs.getActionContext() == null || Mvcs.getActionContext().getRequest() == null || Mvcs.getMessage(Mvcs.getActionContext().getRequest(), msg) == null) {
            this.msg = Strings.sNull(msg);
        } else {
            this.msg = Mvcs.getMessage(Mvcs.getActionContext().getRequest(), msg);
        }
        return this;
    }

    public Result addData(Object data) {
        this.data = data;
        return this;
    }

    public Result(int code, String msg, Object data) {
        this.code = code;
        if (Strings.isBlank(msg) || Mvcs.getActionContext() == null || Mvcs.getActionContext().getRequest() == null || Mvcs.getMessage(Mvcs.getActionContext().getRequest(), msg) == null) {
            this.msg = Strings.sNull(msg);
        } else {
            this.msg = Mvcs.getMessage(Mvcs.getActionContext().getRequest(), msg);
        }
        this.data = data;
    }

    public static Result success(String content) {
        return new Result(0, content, null);
    }

    public static Result success(String content, Object data) {
        return new Result(0, content, data);
    }

    public static Result success(Object data) {
        return new Result(0, "system.success", data);
    }
    public static Result successNonNull(Object data) {
        return new Result(0, "system.success", Objects.requireNonNull(data));
    }

    public static Result error(int code, String content) {
        return new Result(code, content, null);
    }

    public static Result error(String msg,Object data){
        return new Result(-1,msg,data);
    }

    public static Result error(String content) {
        return new Result(-1, content, null);
    }

    public static Result success() {
        return new Result(0, "system.success", null);
    }

    public static Result error() {
        return new Result(-1, "system.error", null);
    }


    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public Object getData() {
        return data;
    }

    public String toJsonString() {
        return Json.toJson(this, JsonFormat.compact());
    }

    public Result setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

    public String getDetail() {
        return detail;
    }

    public Result addKey(String key) {
        this.key = key;
        return this;
    }

    public enum  HTTP_STATUS{
        OK(200),ERROR(500);
        public final Integer CODE;
        HTTP_STATUS(Integer code) {
            this.CODE = code;
        }
    }
    public static <K,V> Map<K,V> createMap(Object... args) {
        TreeMap<K, V> map = new TreeMap<>();
        for (int i = 0; i < args.length; i+=2) {
            map.put((K)args[i],(V)args[i+1]);
        }
        return map;
    }
    public static <K,V> Map<K,V> createHashMap(Object... args) {
        HashMap<K, V> map = new HashMap<>();
        for (int i = 0; i < args.length; i+=2) {
            map.put((K)args[i],(V)args[i+1]);
        }
        return map;
    }
}

